package pro.spring.controller.frontController;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.mail.Multipart;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.connector.Request;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.HttpServletBean;

import pro.spring.model.Images;
import pro.spring.model.Users;



@Controller
@RequestMapping("usr")
public class FUsersController extends BaseController implements ServletContextAware{
	private String local = "page/front/user/";
	private ServletContext servletContext;
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext  = context;
	}
	@RequestMapping(value="{id}.html",method=RequestMethod.GET)
	public String list(@PathVariable int id,ModelMap map){
		map.put("one",usersService.selectByPrimaryKey(id));
		return local+"usee";
	}
	
	@RequestMapping(value="edit/{id}.html",method=RequestMethod.GET)
	public String edit(@PathVariable int id,ModelMap map, HttpServletRequest request){
		map.put("one",usersService.selectByPrimaryKey(id));
		return local+"edit";
	}
	@RequestMapping(value="edit/doedit.html",method=RequestMethod.POST)
	public String doEdit(Users users,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request)throws Exception{
		Users originalUsers = usersService.selectByPrimaryKey(users.getuId());
		originalUsers.setuName(users.getuName());
		originalUsers.setuSex(users.getuSex());
		originalUsers.setuAge(users.getuAge());
		originalUsers.setuBirthday(users.getuBirthday());
		originalUsers.setuPhone(users.getuPhone());
		int infoStatus=usersService.updateByPrimaryKey(originalUsers);
		int imageStatus=1;
		if(!file.isEmpty()){
			System.out.println("have image file upload");
			//String path = request.getSession().getServletContext().getRealPath("/")+"upload\\images\\";
			String path = this.servletContext.getRealPath("/page/upload/images/");  //获取本地存储路径
			String imageName=new Date().getTime() + originalUsers.getuId()+"EX"+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			File exImage= new File(path,imageName);
			try {
			    file.getFileItem().write(exImage); //将上传的文件写入新建的文件中
			    Images images=new Images();
			    images.setImName(originalUsers.getuName()+"的头像");
			    images.setImLoclhost(imageName);
			    images.setUsersUId(originalUsers.getuId());
			    imageStatus=imagesService.insert(images);
			    Users imageUser = usersService.selectByPrimaryKey(originalUsers.getuId());
				imageUser.setImgaesImId(images.getImId());
				usersService.updateByPrimaryKey(imageUser);
			} catch (Exception e) {
				imageStatus=0;
			    e.printStackTrace();
			}
		}
		String returnpath="redirect:../"+originalUsers.getuId()+".html";
		return returnpath;
	}
	@RequestMapping(value="edit/editimage.html",method=RequestMethod.GET)
	public String editImage(int uId,ModelMap map){
		map.put("one",usersService.selectByPrimaryKey(uId));
		return local+"jcropdemo";
	}
	@ResponseBody
	@RequestMapping(value="edit/editnow.json",method=RequestMethod.POST)
	public int editImage(int uId,int x1,int y1,int w,int h){
		try{
			Images images = imagesService.selectByPrimaryKey(usersService.selectByPrimaryKey(uId).getImgaesImId());
			String imagePath=this.servletContext.getRealPath("/page/upload/images/")+"/"+images.getImLoclhost();
			//String imagePath="E://EclipseWorkspace//.metadata//.plugins//org.eclipse.wst.server.core//tmp1//wtpwebapps//wkxx//page//upload//images//1411197816955EX.jpg";
			System.out.println(imagePath);
			Image img;
			ImageFilter cropFilter;
			BufferedImage bi= ImageIO.read(new File(imagePath));
			int srcWidth = bi.getWidth();
			int srcHeight = bi.getHeight();
			if(srcWidth>=w&&srcHeight>=h){
				Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
//				int x1=x*srcWidth/400;
//				int y1=y*srcHeight/270;
//				int w1=w*srcWidth/400;
//				int h1 =h*srcHeight/270;
				cropFilter = new CropImageFilter(x1,y1,w,h);
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "JPEG", new File(imagePath));
			}
			return 1;
		}catch(IOException e){
			e.printStackTrace();
			return 0;
		}
	
	}
	
}
